import Taro from '@tarojs/taro'
import {HTTP_STATUS} from '@/constants/status'
import config from '@/config/index'

export default {
  baseOptions (params, method = 'GET') {
    let {url, data} = params
    let contentType = 'application/json'
    contentType = params.contentType || contentType
    type OptionType = {
      url: string,
      data?: object | string,
      method?: any,
      header: {
        [key: string]: string
      },
      success?: any,
      xhrFields: object,
      error?: any
    }

    data = {
      ...data,
      timestamp: new Date().getDate(),
      cookie: Taro.getStorageSync('cookies')
    }
    const options: OptionType = {
      url: url.indexOf('http') !== -1 ? url : config.baseUrl + url,
      data,
      method,
      header: {
        'content-type': contentType,
      },
      xhrFields: {withCredentials: true}
    }
    let token = Taro.getStorageSync('token')
    if (token) {
      options.header.token = token
    }
    return Taro.request(options)
  },
  setCookie (res: {
    cookies: Array<{
      name: string,
      value: string,
      expires: string,
      path: string
    }>,
    header: {
      'Set-Cookie': string
    }
  }, url) {
    if (res.cookies && res.cookies.length > 0 && url.indexOf('login/cellphone') !== -1) {
      let cookies = ''
      res.cookies.forEach((cookie, index) => {
        // windows的微信开发者工具返回的是cookie格式是有name和value的,在mac上是只是字符串的
        if (cookie.name && cookie.value) {
          cookies += index === res.cookies.length - 1 ? `${cookie.name}=${cookie.value};expires=${cookie.expires};path=${cookie.path}` : `${cookie.name}=${cookie.value}`
        } else {
          cookies += `${cookie}`
        }
      })
      Taro.setStorageSync('cookies', cookies)
    }
  },
  async dealWith (result, url) {
    try {
      let res = await result
      this.setCookie(res, url) // 更新Cookie
      // if (res.data.code) {
      //   let pages = Taro.getCurrentPages();
      //   console.log(pages)
      //   let currentPage = pages[pages.length - 1]
      //   console.log(currentPage)
      //   await Taro.showToast({
      //     title: '身份已过期，1秒后跳转到登录界面',
      //     icon: 'none'
      //   })
      //   await Taro.clearStorage()
      //   setTimeout(() => {
      //     Taro.navigateTo({
      //       url: '/pages/User/Login/index'
      //     })
      //   }, 1000)
      // }
      switch (res.data.status) {
        case HTTP_STATUS.NOT_FOUND:
          console.log('请求资源不存在')
          break
        case HTTP_STATUS.BAD_GATEWAY:
          console.log('服务端出现了问题')
          break
        case HTTP_STATUS.FORBIDDEN:
          console.log('没有权限访问')
          break
        case HTTP_STATUS.AUTHENTICATE:
          Taro.clearStorage()
          Taro.navigateTo({
            url: 'pages/packageA/page/login/index'
          })
          console.log('请先登录')
          break
        case HTTP_STATUS.SERVER_ERROR:
          Taro.showToast({
            title: '服务器异常，请稍后重试',
            icon: 'none'
          })
          break
        // case 400:
        // let pages = Taro.getCurrentPages();
        // console.log(pages)
        // let currentPage = pages[pages.length - 1]
        // console.log(currentPage)
        // await Taro.showToast({
        //   title: '身份已过期，1秒后跳转到登录界面',
        //   icon: 'none'
        // })
        // await Taro.clearStorage()
        // setTimeout(() => {
        //   Taro.navigateTo({
        //     url: '/pages/User/Login/index'
        //   })
        // }, 1000)
        // break
        default:
          return res.data
      }
    } catch (e) {
      console.log('请求错误', e)
    }
  },
  get (url, data?: object) {
    let option = {url, data}
    return this.dealWith(this.baseOptions(option), url)
  },
  post (url, data?: object, contentType?: string) {
    let params = {url, data, contentType}
    return this.dealWith(this.baseOptions(params, 'POST'), url)
  },
  put (url, data?: object) {
    let option = {url, data}
    return this.dealWith(this.baseOptions(option, 'PUT'), url)
  },
  delete (url, data?: object) {
    let option = {url, data}
    return this.dealWith(this.baseOptions(option, 'DELETE'), url)
  }
}
